<?php
/*
    subtlety - profile info is initialized in $User initialization
    so if anything changes here, $User needs to refresh things so
    they are up to date when we use them here.

    A prophylactic option - refresh after todo section.
*/

error_reporting(E_ALL);
$relPath='./pinc/';
include_once($relPath.'site_vars.php');
require_once $relPath."dpinit.php";
include_once($relPath.'dp_main.inc');
// include_once($relPath.'prefs_options.inc');
// include_once($relPath.'theme.inc');
// include_once($relPath.'links.inc');
include_once($relPath.'js_newpophelp.inc');

$todo               = Arg("todo");
$real_name          = Arg("real_name");
$profilename        = Arg("profilename");
$credit_name        = Arg("credit_name");
$tab                = Arg("tab", "proof");
$email_updates      = Arg("email_updates");
$auto_proj_thread   = Arg("auto_proj_thread");
$send_to_post       = Arg("send_to_post");
$v_zoom             = Arg("v_zoom");
$h_zoom             = Arg("h_zoom");
$v_tframe           = Arg("v_tframe");
$h_tframe           = Arg("h_tframe");
$v_tscroll          = Arg("v_tscroll");
$h_tscroll          = Arg("h_tscroll");
$v_tlines           = Arg("v_tlines");
$h_tlines           = Arg("h_tlines");
$v_tchars           = Arg("v_tchars");
$h_tchars           = Arg("h_tchars");
$v_twrap            = Arg("v_twrap");
$h_twrap            = Arg("h_twrap");
$i_pmdefault        = Arg("i_pmdefault");
$cp_anonymous       = Arg("cp_anonymous");
$tp_anonymous       = Arg("tp_anonymous");
$ip_anonymous       = Arg("ip_anonymous");
$pp_anonymous       = Arg("pp_anonymous");
$pm_anonymous       = Arg("pm_anonymous");
$credit_name        = Arg("credit_name");
$u_privacy          = Arg("u_privacy");
$i_res              = Arg("i_res");
$i_newwin           = Arg("i_newwin");
$i_toolbar          = Arg("i_toolbar");
$i_layout           = Arg("i_layout");
$i_statusbar        = Arg("i_statusbar");
$v_font_face        = Arg("v_font_face");
$v_font_size        = Arg("v_font_size");
$h_font_face        = Arg("h_font_face");
$h_font_size        = Arg("h_font_size");
$i_pmdefault        = Arg("i_pmdefault");
$u_align            = Arg("u_align");
$is_special_colors  = Arg("is_special_colors");

$chk_cp             = IsArg("chk_cp");
$chk_ip             = IsArg("chk_ip");
$chk_tp             = IsArg("chk_tp");
$chk_pm             = IsArg("chk_pm");
$chk_pp             = IsArg("chk_pp");
$is_save_profile    = IsArg("saveasprofile");


switch($todo)
{
    case 'setprofile':
        // a different named profile has been selected. 
        // js should have set profilename to which one.
        // (We must be on tab 1)
        // LogMsg("todo setprofile {$profilename}");
        $User->SetProfile($profilename);
        break;

    case 'addprofile': // can only happen on tab 1
        // LogMsg("todo addprofile {$profilename}");
        save_profile($profilename, $i_res, 
            $i_layout, $i_newwin, $i_toolbar,
            $i_statusbar, $v_font_face, $v_font_size, $v_zoom,
            $v_tframe, $v_tscroll, $v_tlines, $v_tchars,
            $v_twrap, $h_font_face, $h_font_size, $h_zoom,
            $h_tframe, $h_tscroll, $h_tlines, $h_tchars,
            $h_twrap);
        $User->SetProfile($profilename);
        break;

    case 'update':
        // LogMsg("todo $todo tab = $tab");
        switch($tab)
        {
            case "general":
                save_general_tab($real_name, $email_updates, 
                        $u_privacy, $credit_name, $chk_cp,
                        $chk_ip, $chk_tp, $chk_pm, $chk_pp);
                break;

            case "pm":
                save_pm_tab($i_pmdefault, $auto_proj_thread, 
                                            $send_to_post); 
                break;

            default:
                save_profile(null, $i_res, 
                    $i_layout, $i_newwin, $i_toolbar,
                $i_statusbar, $v_font_face, $v_font_size, $v_zoom,
                    $v_tframe, $v_tscroll, $v_tlines, $v_tchars,
                    $v_twrap, $h_font_face, $h_font_size, $h_zoom,
                    $h_tframe, $h_tscroll, $h_tlines, $h_tchars,
                    $h_twrap);
                break;
        }
}

$User->RefreshProfile($User->Username());


// header, start of table, form, etc. common to all tabs
$headertitle = _("Personal Preferences");
theme_header($headertitle);
echo "
<script type='text/javascript'>
    function pform()
    {
        return document.prefform;
    }

    function get_todo()
    {
        return pform().todo.value;
    }

    function set_todo(val)
    {
        pform().todo.value = val;
    }

    function UpdatePrefs()
    {
        set_todo('update');
        document.prefform.submit();
    }

    function AddProfile()
    {
        set_todo('addprofile');
        return true;
    }

    function TestProfileName()
    {
        pform().saveasprofile.disabled
            = (pform().newprofilename.value.length > 0
                ? '' : 'disabled');
    }

    function UpdateQuit()
    {
        set_todo('updatequit');
        document.prefform.submit();
        Quit();
    }

    function SelectProfile()
    {
        set_todo('setprofile');
        document.prefform.profilename.value
            = document.prefform.selprofilename.value;
        document.prefform.submit();
    }

    function Quit()
    {
        window.close();
    }
</script>
<br>
<div class='left w75'>
<form name='prefform' id='prefform' method='POST'>
<input type='hidden' name='todo' id='todo' value=''>
<input type='hidden' name='tab' value='$tab'>
<input type='hidden' name='profilename' 
                    value='{$User->ActiveProfileName()}'>
<table id='tblprefs' class='white prefs w90'>

<tr><td class='headerbar prefs center' colspan='6'>
<h1>".sprintf(_("Preferences Page for %s"), $User->Username())."</h1>
<h2>"._("Your preferences are grouped into tabs. 
    Switch among the tabs by clicking on e.g. 
    'General' or 'Proofreading'.")."<br/>
    "._("(click the ? for help on that specific preference)")."</h2>
</td></tr>\n";

echo "
<tr><td colspan='6' class='tabsbar left'>
    <div id='tabs'>
    <ul>
        <li id='generaltab'"
            .($tab == 'general' ? " class='current'" : "").">
        <a href='$code_url/userprefs.php?tab=general'>"
            ._("General")
            ."</a>
        </li>
        <li id='prooftab'"
                .($tab == 'proof' ? " class='current'" : "").">
        <a href='$code_url/userprefs.php?tab=proof'>"
            ._("Proofreading")
            ."</a>
        </li>\n";

if($User->IsProjectManager())
{
    echo "
        <li id='pmtab'"
                .($tab == 'pm' ? " class='current'" : "").">
        <a href='$code_url/userprefs.php?tab=pm'>"
        ._("Managing projects")
        ."</a>
        </li>\n";
}

echo "
    </ul>
    </div>
</td></tr>\n";

// display one of the tabs

switch($tab)
{
    case 'proof':
        echo_proofreading_tab();
        break;
    case 'pm':
        if($User->IsProjectManager())
            echo_pm_tab();
        else
            echo_general_tab();
        break;
    default:
        echo_general_tab();
        break;
}

echo "
</table>
</form>
<br>
</div>";

theme_footer();

// End main code. Functions below.
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

/*************** TO GENERATE TABS ***************/

// Produce tabs 

/*************** GENERAL TAB ***************/

function echo_general_tab() 
{
    global $reset_password_url;
    global $User;
    global $dpdb;
    global $pophelp_name;

    $i_stats = array(_("Public"), _("Anonymous"), _("Private"));


    $real_name = $User->RealName();
    $email = $User->EmailAddress();


    show_text_pref('Name', 'real_name', 'name', $real_name);

    td_label("Password");
    echo "
    <td class='middle white left'>
    <a href='$reset_password_url'>"._("Reset password")."</a>
    </td>\n";
    td_pophelp('password');

    echo "
    </tr>
    <tr>\n";

    show_list_pref(_('Privacy'), 'u_privacy', 'privacy',
        $User->Privacy(), $i_stats);
    show_blank();

    echo "
    </tr>
    <tr>\n";

    show_credits_wanted();

    show_text_pref(_('Credit Name'), 'credit_name', 'credit_name',
                        $User->CreditName());
    echo "</tr>\n";

    echo_bottom_button_row();
}

function save_general_tab($real_name, $email_updates, 
                            $u_privacy, $credit_name, $chk_cp,
                            $chk_ip, $chk_tp, $chk_pm, $chk_pp)
{
    global $dpdb;
    global $User;
    global $real_name;

    // set users values
    $sql = "UPDATE users
            SET
                real_name       = '$real_name',
                email_updates   = '$email_updates',
                u_privacy       =  $u_privacy
            WHERE username='{$User->Username()}'";

    $dpdb->SqlExecute($sql);
            
    // Opt-out Content-Provider credits (deprecated), Image Preparer, 
    // Text Preparer, Project-Manager and/or Post-Processer.
    $User->SetBoolean('cp_anonymous', ! $chk_cp);
    $User->SetBoolean('ip_anonymous', ! $chk_ip);
    $User->SetBoolean('tp_anonymous', ! $chk_tp);
    $User->SetBoolean('pm_anonymous', ! $chk_pm);
    $User->SetBoolean('pp_anonymous', ! $chk_pp);
    // Credit Real Name, Username or Other (specify)
    $User->SetCreditName($credit_name);
}

/*************** PROOFREADING TAB ***************/

function echo_proofreading_tab() 
{
    global $User;
    global $Context;
    global $dpdb;

    // dump($User);
    // die();
    
    $username = $User->Username();
    $activeprofilename = $User->ActiveProfileName();

    $profiles = $dpdb->SqlRows("
                    SELECT DISTINCT profilename 
                    FROM user_profiles 
                    WHERE username = '$username'
                    ORDER BY profilename");
    $pf_num = count($profiles);

    echo "<tr>\n";

    td_label_long(6, _('Profiles'));

    echo "
    </tr>
    <tr><td class='prefsbar right'>
    "._("Current profile:")."</td>

    <td>
    <select name='selprofilename' id='selprofilename'
            onchange='SelectProfile();'>\n";

    foreach($profiles as $profile)
    {
        $pfname = $profile['profilename'];
        echo "<option value='$pfname'";
        if ($pfname == $User->ActiveProfileName()) 
        { 
            echo " SELECTED"; 
        }
        echo ">$pfname</option>\n";
    }
    echo "
    </select>
    </td>\n";
    td_pophelp('switch');
    echo "
    <td class='prefsbar right'> "._("Save as profile:")."</td>
    <td>
    <input type='text' name='newprofilename' 
                                onkeyup='TestProfileName();'>
    <input type='submit' name='saveasprofile' onclick='AddProfile();'
            disabled='disabled' value='"._("Add profile")."'>
    </td>
    <td>&nbsp;</td>\n";



    echo "
    </tr>
    <tr>\n";

    show_blank();

    show_radio_pref('Launch in new window', 'i_newwin', 'newwindow',
                $User->IsNewWindow(), array(1=>_("Yes"),0=>_("No")));

    echo "
    </tr>
    <tr>\n";

/*
    show_radio_pref('Interface type', 'i_type', 'facetype',
    $User->InterfaceIndex(), 
                    array(0=>_("Standard"), 1=>_("Enhanced")));

    show_radio_pref('Show toolbar', 'i_toolbar', 'toolbar',
                $User->IsToolbar(), array(1=>_("Yes"),0=>_("No")));
    show_blank();

    echo "
    </tr>
    <tr>\n";
*/

    show_radio_pref(_('Interface layout'), 'i_layout', 'layout',
                    $User->LayoutIndex(),
        array(
            1 => 'Vertical <img
                        src="tools/proofers/gfx/bt4.png" width="26" 
                alt="'._("Vertical").'">',
            0 => 'Horizontal <img
                        src="tools/proofers/gfx/bt5.png" width="26" 
                alt="'._("Horizontal").'">'));

    show_radio_pref('Show status bar', 'i_statusbar', 'statusbar',
    $User->ShowStatusBar(), array(1=>_("Yes"),0=>_("No")));

    echo "
    </tr>
    <tr>\n";

    td_label_long(2,
        "<img alt='vlayout'
          src='tools/proofers/gfx/bt4.png'>"._("Vertical layout"));
    td_pophelp('vertprefs');
    td_label_long(2,
        "<img alt='hlayout'
          src='tools/proofers/gfx/bt5.png'>"._("Horizontal layout"));
    td_pophelp('horzprefs');

    echo "
    </tr>
    <tr>\n";

    show_list_pref('Font Face', 'v_font_face', 'v_font_face',
            $User->VerticalFontFace(), $Context->FontFaces());

    show_list_pref('Font Face', 'h_font_face', 'h_font_face',
            $User->HorizontalFontFace(), $Context->FontFaces());

    echo "
    </tr>
    <tr>\n";

    show_list_pref('Font size (pt)', 'v_font_size', 'v_font_size',
            $User-> VerticalFontSize(), $Context->FontSizes());

    show_list_pref('Font size (pt)', 'h_font_size', 'h_fon_tsize',
            $User-> HorizontalFontSize(), $Context->FontSizes());

    echo "
    </tr>
    <tr>\n";

    show_text_pref('Image zoom', 'v_zoom', 'v_zoom',
            $User->VerticalZoom(), 3, " %");

    show_text_pref('Image zoom', 'h_zoom', 'h_zoom', 
                $User->HorizontalZoom(), 3, " %");

    echo "
    </tr>
    <tr>\n";

    show_text_pref('Text window width', 'v_tframe', 'v_textsize',
        $User->VerticalTextFramePct(), 3, " %");

    show_text_pref('Text window height', 'h_tframe', 'h_textsize',
        $User->HorizontalTextFramePct(), 3, " %");


    echo "
    </tr>
    <tr>\n";

    show_radio_pref('Scroll text', 'v_tscroll', 'v_scroll',
        $User->IsVerticalTextScroll(), array(1=>_("Yes"),0=>_("No")));

    show_radio_pref('Scroll text', 'h_tscroll', 'h_scroll',
    $User->IsHorizontalTextScroll(), array(1=>_("Yes"),0=>_("No")));

    echo "
    </tr>
    <tr>\n";

    show_text_pref('Editor height', 'v_tlines', 'v_textlines', 
            $User->VerticalTextLines(), 3, _(" lines (0=auto)"));

    show_text_pref('Editor height', 'h_tlines', 'h_textlines', 
            $User->HorizontalTextLines(), 3, _(" lines (0=auto)"));

    echo "
    </tr>
    <tr>\n";

    show_text_pref('Editor width', 'v_tchars', 'v_textlength', 
        $User->VerticalTextChars(), 3, _(" characters (0=auto)"));

    show_text_pref("Editor width", "h_tchars", "h_textlength", 
        $User->HorizontalTextChars(), 3, _(" characters (0=auto)"));

    echo "
    </tr>
    <tr>\n";

    show_radio_pref('Wrap text', 'v_twrap', 'v_wrap',
            $User->VerticalWrap(), array(1=>_("Yes"),0=>_("No")));

    show_radio_pref('Wrap text', 'h_twrap', 'h_wrap',
            $User->HorizontalWrap(), array(1=>_("Yes"),0=>_("No")));


    echo "
    </tr>
    <tr><td colspan='6' class='white center'>\n";


    // buttons
    echo "<input type='submit' value='" . _("Save Preferences")
        . "' name='save' onclick='UpdatePrefs();'> &nbsp;
        <input type='button' name='quit' value='" . _("Quit")."'
            onclick='Quit()'>
    </td></tr>\n";
}

function save_profile($profilename, $i_res,
        $i_layout, $i_newwin, $i_toolbar, $i_statusbar, $v_font_face,
        $v_font_size, $v_zoom, $v_tframe, $v_tscroll, $v_tlines,
        $v_tchars, $v_twrap, $h_font_face, $h_font_size, $h_zoom,
        $h_tframe, $h_tscroll, $h_tlines, $h_tchars, $h_twrap) 
{
    global $User;

    if(! $profilename)
        $profilename = $User->ActiveProfileName();
    // LogMsg("save_profile $profilename");
    // set user_profiles values
    $args = Array(
           "i_res"           => $i_res,
           "i_layout"        => $i_layout,
           "i_newwin"        => $i_newwin,
           "i_toolbar"       => $i_toolbar,
           "i_statusbar"     => $i_statusbar,
           "v_font_face"     => $v_font_face,
           "v_font_size"     => $v_font_size,
           "v_zoom"          => $v_zoom,
           "v_tframe"        => $v_tframe,
           "v_tscroll"       => $v_tscroll,
           "v_tlines"        => $v_tlines,
           "v_tchars"        => $v_tchars,
           "v_twrap"         => $v_twrap,
           "h_font_face"     => $h_font_face,
           "h_font_size"     => $h_font_size,
           "h_zoom"          => $h_zoom,
           "h_tframe"        => $h_tframe,
           "h_tscroll"       => $h_tscroll,
           "h_tlines"        => $h_tlines,
           "h_tchars"        => $h_tchars,
           "h_twrap"         => $h_twrap);
    $User->UpdateProfile($args, $profilename);

    global $is_special_colors;
    $User->SetBoolean('hide_special_colors', 
            $is_special_colors == 'no');
}

/*************** PM TAB ***************/

function echo_pm_tab() 
{
    global $User;

    echo "<tr>\n";
    $auto_proj_thread = $User->Setting('auto_proj_thread');
    $send_to_post = ($User->Setting('send_to_post') == 'yes'); 
    show_list_pref('Automatically watch your project threads', 
                            'auto_proj_thread', 'auto_thread',
                            ($auto_proj_thread ? 'yes' : 'no'),
                            array('yes'=>_('Yes'),'no'=>_('No')));
    echo "</tr>\n";
    echo "<tr>\n"; 
    show_list_pref('Automatically send your projects to 
                                    the post-processing pool', 
                            'send_to_post', 'pmto_post', 
                            ($send_to_post ? 'yes' : 'no'), 
                            array('yes'=>_('Yes'),'no'=>_('No'))); 
    echo "</tr>\n"; 

    echo_bottom_button_row();

    echo "</td></tr>\n";
}

function save_pm_tab($i_pmdefault, $auto_proj_thread, $send_to_post) 
{
    global $dpdb;
    global $User;

    $sql = "UPDATE users
            SET i_pmdefault = {$i_pmdefault}
            WHERE username='{$User->Username()}'";
    $dpdb->SqlExecute($sql);

    // does PM want to be signed up for email notifications of
    // replies made to their project threads

    $User->SetBoolean('auto_proj_thread', $auto_proj_thread == 'yes');
 
    // remember if the PM wants to have their projects assigned 
    // to them for PP 
    $User->SetBoolean('send_to_post', $send_to_post == 'yes');
}

// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

function echo_bottom_button_row()
{
    echo "
    <tr><td colspan='6' class='white center'>
        <input name='saveprefs' type='submit' 
            onclick='UpdatePrefs()'
            value='"._("Save Preferences")."'>
        <input type='button' name='quit' value='" . _("Quit")."' 
            onclick='Quit();'>
    </td></tr>\n";
}

// ---------------------------------------------------------

function show_credits_wanted()
{
    global $User;
    $lbl = _("Credits wanted");
    $checked_cp = ($User->Setting('cp_anonymous') ? '' : ' checked');
    $checked_ip = ($User->Setting('ip_anonymous') ? '' : ' checked');
    $checked_tp = ($User->Setting('tp_anonymous') ? '' : ' checked');
    $checked_pm = ($User->Setting('pm_anonymous') ? '' : ' checked');
    $checked_pp = ($User->Setting('pp_anonymous') ? '' : ' checked');

    td_label("$lbl:");

    echo "
<td class='middle white left'>
CP-<input type='checkbox' name='chk_cp' $checked_cp>&nbsp;&nbsp;
IP-<input type='checkbox' name='chk_ip' $checked_ip>&nbsp;&nbsp;
TP-<input type='checkbox' name='chk_tp' $checked_tp>&nbsp;&nbsp;";
    if ($User->IsProjectManager())
        echo "
PM-<input type='checkbox' name='chk_pm' $checked_pm>&nbsp;&nbsp;";
echo "
PP-<input type='checkbox' name='chk_pp' $checked_pp>
</td>\n";

    td_pophelp("creditswanted");
}


// ---------------------------------------------------------

function _show_credit_name()
// Handles 'credit_name' 
{
    global $User;

    $credit_name = $User->Setting('credit_name');
    if(! $credit_name) 
        $credit_name = $User->Setting('real_name');
    
    $credit_name = h($credit_name);

    echo " <input type='text' name='credit_name' 
                        value='$credit_name'>\n";
}

// ---------------------------------------------------------

function show_text_pref($label, $fieldname, $pophelp_name, 
                         $cur_val, $size = "", $rest = "")
{
    td_label(_("$label:"));
    echo "
    <td class='middle white left'>
    <input type='text' name='$fieldname' value='$cur_val' "
        . ($size ? "size='$size'" : "")
        . ">$rest</td>\n";
    td_pophelp($pophelp_name);
}

function show_list_pref($label, $fieldname, $pophelp_name, 
                                $cur_val, $options = null)
{
    td_label(_("$label:"));
    echo "
    <td class='middle white left'>
    <select name='$fieldname' id='$fieldname'>\n";
    foreach ($options as $option_value => $option_label)
    {
        echo "<option value='$option_value'";
        if ($option_value == $cur_val) 
        { 
            echo " SELECTED"; 
        }
        echo ">$option_label</option>\n";
    }
    echo "
    </select>
    </td>\n";
    td_pophelp($pophelp_name);
}

function show_radio_pref($label, $field_name, $pophelp_name,
                                $cur_value, $options)
{
    td_label(_("$label:"));
    echo "
    <td class='middle white left'>\n";

    foreach ($options as $val => $lbl)
    {
        echo "<input type='radio' name='$field_name' value='$val'" 
            . (mb_strtolower($val) == mb_strtolower($cur_value)
                                    ? " CHECKED" 
                                    : "")
        . ">$lbl&nbsp;&nbsp;\n";
    }
    echo "
    </td>\n";
    td_pophelp($pophelp_name);
}

// ---------------------------------------------------------

function show_blank()
{
    td_label("&nbsp;");
    echo "
    <td class='middle white left'>&nbsp;</td>
    <td class='white center'>&nbsp;</td>\n";
}

// ---------------------------------------------------------

function td_label($label)
{
    echo "
    <td class='prefsbar right'>
        $label
    </td>\n";
}

function td_label_long($colspan, $label)
{
    echo "
    <td class='prefsbar center' colspan='$colspan'>
        $label
    </td>\n";
}

function td_pophelp($pophelp_name)
{
    echo "
    <td class='center'>
        <a href='newHelpWin(\"$pophelp_name\");'> ? </a>
    </td>\n";
}

// vim: sw=4 ts=4 expandtab
?>
